package com.wzk.travelspringboot.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzk.travelspringboot.controller.admin.dto.TicketOrderDTO;
import com.wzk.travelspringboot.dto.Result;
import com.wzk.travelspringboot.entity.TicketOrder;
import com.wzk.travelspringboot.service.TicketOrderService;
import com.wzk.travelspringboot.vo.ScenicOrderVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangzikang
 */
@Slf4j
@RestController
@RequestMapping("/admin/ticket")
@RequiredArgsConstructor
@Validated
public class AdminTicketOrderController {

    private final TicketOrderService ticketOrderService;

    /**
     * 核销门票
     */
    @PostMapping("/used")
    public Result usedTicket(@RequestBody @NotBlank(message = "核销的订单号不能为空") String on) {
        return ticketOrderService.usedTicket(on);
    }

    /**
     * 多条件筛选景区门票数据
     */
    @GetMapping("/search")
    public Result searchTicketData(TicketOrderDTO dto) {
        return ticketOrderService.searchTicketOrder(dto);
    }

    /**
     * 分页查询所有门票订单
     * 关联查询景区名称
     */
    @GetMapping("/list")
    public Result listAllTicketOrders(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        // 使用关联查询的服务方法，返回包含景区名称的订单数据
        return ticketOrderService.queryOrdersWithScenicName(pageNum, pageSize);
    }

    /**
     * 查询所有已核销的门票信息，按时间降序排列
     */
    @GetMapping("/used/list")
    public Result listAllUsedTickets(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        // 创建分页对象
        Page<TicketOrder> page = new Page<>(pageNum, pageSize);
        
        // 创建查询条件，筛选已核销的门票，并按创建时间降序排序
        LambdaQueryWrapper<TicketOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TicketOrder::getUsed, true)
                   .orderByDesc(TicketOrder::getCreateTime);
        
        // 查询数据
        Page<TicketOrder> orderPage = ticketOrderService.page(page, queryWrapper);
        List<TicketOrder> orderList = orderPage.getRecords();
        
        // 如果订单列表为空，返回空结果
        if (orderList.isEmpty()) {
            return Result.success("暂无已核销门票数据", new ArrayList<>());
        }
        
        // 关联查询景区信息，创建包含景区名称的VO对象
        List<ScenicOrderVO> voList = new ArrayList<>(orderList.size());
        for (TicketOrder order : orderList) {
            ScenicOrderVO vo = ticketOrderService.convertToVO(order);
            voList.add(vo);
        }
        
        // 创建返回的分页对象
        Page<ScenicOrderVO> voPage = new Page<>(pageNum, pageSize, orderPage.getTotal());
        voPage.setRecords(voList);
        
        return Result.success("查询成功", voPage);
    }

    /**
     * 根据订单号查询订单详情
     */
    @GetMapping("/detail")
    public Result getTicketOrderDetail(@RequestParam @NotBlank(message = "订单号不能为空") String orderNumber) {
        LambdaQueryWrapper<TicketOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TicketOrder::getOrderNumber, orderNumber);
        TicketOrder order = ticketOrderService.getOne(queryWrapper);
        if (order == null) {
            return Result.failed("订单不存在");
        }
        return Result.success(order);
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel")
    public Result cancelTicketOrder(@RequestBody @NotBlank(message = "订单号不能为空") String orderNumber) {
        return ticketOrderService.cancelOrder(orderNumber);
    }

    /**
     * 根据用户ID查询订单
     */
    @GetMapping("/user/{userId}")
    public Result getOrdersByUserId(@PathVariable("userId") @NotNull(message = "用户ID不能为空") Long userId) {
        return ticketOrderService.queryOrderByUserId(userId);
    }

    /**
     * 根据景区ID查询订单
     */
    @GetMapping("/scenic/{scenicId}")
    public Result getOrdersByScenicId(
            @PathVariable("scenicId") @NotNull(message = "景区ID不能为空") Long scenicId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<TicketOrder> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<TicketOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TicketOrder::getScenicId, scenicId);
        Page<TicketOrder> orderPage = ticketOrderService.page(page, queryWrapper);
        return Result.success(orderPage);
    }

    /**
     * 根据订单状态查询订单
     */
    @GetMapping("/state/{state}")
    public Result getOrdersByState(
            @PathVariable("state") @NotNull(message = "订单状态不能为空") Integer state,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<TicketOrder> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<TicketOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TicketOrder::getState, state);
        Page<TicketOrder> orderPage = ticketOrderService.page(page, queryWrapper);
        return Result.success(orderPage);
    }
}
